﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace Cormant.Mvc.Web
{
    [HtmlTag("table")]
    public class MvcGridView : MvcTable
    {
        #region MvcGridView : Constructors.
        public MvcGridView(HtmlHelper html, string id, IEnumerable dataSource)
            : base(html, id)
        {
            this.Columns = new List<MvcGridViewColumn>();
            this.DataSource = dataSource;
        }
        #endregion

        #region MvcGridView : Properties.
        public IList<MvcGridViewColumn> Columns { get; set; }
        public IEnumerable DataSource { get; set; }
        #endregion

        #region MvcGridView : Methods.
        private MvcTableRow AddNewMvcTableRow()
        {
            MvcTableRow row = new MvcTableRow(this.Html);
            this.Rows.Add(row);
            return row;
        }

        private void PrepareRows()
        {
            this.Rows = new List<MvcTableRow>();

            // prepare the table header rows...
            MvcTableRow headerRow = this.AddNewMvcTableRow();
            foreach (MvcGridViewColumn column in this.Columns)
                column.CreateTableCellHeader(this, this.Html);

            // prepare the table data rows...
            if (this.DataSource != null)
            {
                foreach (object dataItem in this.DataSource)
                {
                    MvcTableRow row = this.AddNewMvcTableRow();
                    if (dataItem != null)
                    {
                        foreach (MvcGridViewColumn column in this.Columns)
                            column.CreateTableCell(this, this.Html, dataItem);
                    }
                }
            }
        }

        public override string ToString()
        {
            this.PrepareRows();
            return base.ToString();
        }
        #endregion
    }
}
